$(function(){  
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    //defaults
    $.fn.editable.defaults.url = '/post'; 
    $.fn.editable.defaults.mode = 'popup';
    $.fn.editable.defaults.emptytext = 'vide';
    $.fn.editable.defaults.placement = 'right';
    
    $('#a-id_produit').editable({
        emptytext: ''
    });
    
    $('#a-categorie').editable({
        emptytext: 'aucun',
        inputclass: 'input-medium',
        validate: function(value) {
           if(!value) return 'Veuillez choisir une catégorie';
        }
    }); 
    
    $('#a-famille').editable({
        emptytext: 'Famille',
        inputclass: 'input-medium changeSsf',
        validate: function(value) {
           if(!value) return 'Veuillez choisir une famille';
           $('#id_famille_value').val(value);  
           $('#a-ssfamille').editable('option','source',foamUri+'/sousfamille/xeditable/'+$('#id_famille_value').val());
        }
    }); 
    
    $('#a-ssfamille').editable({
        emptytext: 'Sous-famille',
        validate: function(value) {
           if(!value) return 'Veuillez choisir une sous-famille';
        },
        source: foamUri+'/sousfamille/xeditable/'+$('#id_famille_value').val()
    });
    
    $('#a-gamme').editable({
        emptytext: 'aucun',
        inputclass: 'input-medium'
    }); 
    
    $('#a-ssgamme').editable({
        emptytext: 'aucun',
        inputclass: 'input-medium'
    }); 
        
    $('#a-libelle').editable({
        emptytext: 'Libellé',
        validate: function(value) {
           if($.trim(value) == '') return 'Veuillez saisir un libellé';
        }
    });
    
    $('#a-ingredients').editable({
        emptytext: 'Ingrédients',
        showbuttons: 'bottom',
        placement: 'bottom'
    });
    
    $('#a-code').editable({
       emptytext: 'aucun',
        validate: function(value) {
           if($.trim(value) == '') return 'Veuillez saisir un code';
        }
    });
    
    $('#a-prix').editable({
       emptytext: '0,00',
        validate: function(value) {
           if($.trim(value) == '') return 'Veuillez saisir un prix';
        }
    });
    
    $('#a-ctv').editable({
        emptytext: 'aucun'
    });
    
    $('#a-louvre').editable({
        emptytext: 'aucun'
    });
    
    $('#a-prix_figaro').editable({
        emptytext: '0,00'
    });
    
    $('#a-prix_concession').editable({
        emptytext: '0,00'
    });
    
    $('#a-dlc').editable({
        emptytext: 'DLC',
        validate: function(value) {
           if(!value) return 'Veuillez choisir un DLC';
        }
    });
    
    $('#a-service').editable({
        emptytext: 'Services',
        validate: function(value) {
           if(!value) return 'Veuillez choisir un service';
        }
    });
    
    $('#a-tva_vae').editable({
        emptytext: '0,00'
    });
    
    $('#a-tva_sp').editable({
        emptytext: '0,00'
    });
    
    $('#a-contenant').editable({
        emptytext: 'Contenant',
        validate: function(value) {
           if(!value) return 'Veuillez choisir un contenant';
        }
    });
    
    $('#a-production').editable({
        emptytext: 'Production',
        validate: function(value) {
           if(!value) return 'Veuillez choisir un lieu de production';
        }
    });
    
    $('#a-debut_actif').editable({
        emptytext: dateToDMY(new Date())
    });
    
    $('#a-asavoir').editable({
        emptytext: 'A savoir',
        showbuttons: 'bottom',
    });
    
    $('#a-bio').editable({
        emptytext: 'Bio'
    });
    
    $('#a-lactose').editable({
        emptytext: 'Lactose'
    });
    
    $('#a-allergene').editable({
        emptytext: 'Choisir dans la liste',
        placement: 'top'
    }); 
    
    $('#a-plateau').editable({
        emptytext: 'Choisir dans la liste'
    }); 
    
    $('#a-food_paper_cost').editable({
        emptytext: '0,00'
    });
    
    $('#a-target').editable({
        emptytext: '0,00'
    });
    
    $('#a-marge').editable({
        emptytext: '0,00',
        placement: 'left'
    });
    
    $('#a-volumes-estimes').editable({
        emptytext: '0'
    });
    
    $('#a-seriedix').editable({
        emptytext: '???'
    });
    
    $('#a-fiche-hermes').editable({
        emptytext: '???'
    });
    
    $('#a-fiche-formation').editable({
        emptytext: '???',
        placement: 'left'
    });
    
    $('.editable.notes').editable({
        emptytext: 'Aucun'
    });
    
    $('.editable.notes').editable({
        emptytext: 'Aucun'
    });
    
    $('#a-tps-presence').editable({
        emptytext: 'aucun'
    });
    
    $('#a-prd-complementaire').editable({
        emptytext: 'aucun'
    });
    
    // Get ficheTek for product
    getFichTek(foamUri);   
});

function saveNew(controller){
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $('.editable').editable('submit', {
        url: foamUri+'/'+controller+'/savenew',
        ajaxOptions: {
            dataType: 'json' //assuming json response
        },
        error: function(errors) {
            var msg = '';
            if(errors && errors.responseText) { //ajax error, errors = xhr object
                msg = errors.responseText;
                $('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
                window.location.href = foamUri+'/'+controller;
            } else { //validation error (client-side or server-side)
                $.each(errors, function(k, v) { msg += "- "+v+"<br>"; });
                $('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
            }
        }
    });
}

function saveUpdate(controller){
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $('.editable').editable('submit', {
        url: foamUri+'/'+controller+'/saveupdate',
        ajaxOptions: {
            dataType: 'json' //assuming json response
        },
        error: function(errors) {
            var msg = '';
            if(errors && errors.responseText) { //ajax error, errors = xhr object
                msg = errors.responseText;
                $('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
                window.location.href = foamUri+'/'+controller;
            } else { //validation error (client-side or server-side)
                $.each(errors, function(k, v) { msg += "- "+v+"<br>"; });
                $('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
            }
        }
    });
}

function cancel(controller){
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/fichetechnique/cancel',
        dataType: "html",
        cache: false,
        success: function(contenu){
            window.location.href = foamUri+'/'+controller;  
        }
    }); 
}

function getFichTek(foamUri){
    $.ajax({
        type: 'POST',
        url: foamUri+'/fichetechnique/fiche/'+$('#a-id_produit').text(),
        dataType: "html",
        cache: false,
        success: function(contenu){
            $('.td-fiche-technique').fadeOut('slow');
            $('.td-fiche-technique').html(contenu);
            $('.td-fiche-technique').fadeIn('slow');   
        }
    });    
}

function addFicheElement(){
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("foam");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "foam");
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/fichetechnique/add',
        dataType: "html",
        cache: false,
        success: function(contenu){
            $('#dialog-form').html(contenu);
            $('#id_produit').val($('#a-id_produit').text());
            $("#dialog-form").dialog({
                height: 400,
                width: 285,
                modal: true,
                draggable: false,
                resizable: false,
                show: {
                    effect: "fade",
                    duration: 500
                },
                hide: {
                    effect: "fade",
                    duration: 500
                },
                buttons: {
                    "Ajouter": function() {
                        var flag = true;
                        
                        if($('#id_ingredient').val() === '0'){
                            $('#id_ingredient').css('border-color','red');
                            flag = false;
                        }
                        if($('#quantite').val() === ''){
                            $('#quantite').css('border-color','red');
                            flag = false;
                        }
                        if($('#condition').val() === ''){
                            $('#condition').css('border-color','red');
                            flag = false;
                        }
                        if($('#conservation').val() === ''){
                            $('#conservation').css('border-color','red');
                            flag = false;
                        }
                        if($('#cadencier').val() === ''){
                            $('#cadencier').css('border-color','red');
                            flag = false;
                        }
                        
                        if(flag){
                            $.ajax({
                                type: 'POST',
                                url: foamUri+'/fichetechnique/save',
                                dataType: "html",
                                cache: false,
                                data: {
                                    id_ingredient:$('#id_ingredient').val(),
                                    quantite:$('#quantite').val(),
                                    condition:$('#condition').val(),
                                    conservation:$('#conservation').val(),
                                    cadencier:$('#cadencier').val(),
                                    id_produit:$('#id_produit').val()
                                },
                                success: function(data){
                                    $( "#dialog-form" ).dialog( "close" );
                                    getFichTek(foamUri);
                                }
                            });
                        }
                    },
                    "Annuler": function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {}
            }); 
            $( ".ui-dialog-title" ).text("Ajouter un élément");
        }
    });        
}

function reCss(el){
    $(el).css('border-color','#CCCCCC');
}
